<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="用户名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="displayName">
        <el-input
          v-model="queryParams.displayName"
          placeholder="请输入昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="queryParams.gender"
          placeholder="请选择性别"
          clearable
          style="width: 100%"
        >
          <el-option label="男" value="1" />
          <el-option label="女" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

    
      <el-form-item label="创建时间" prop="createtime">
        <el-date-picker clearable
          v-model="queryParams.createtime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否删除" prop="deleted">
        <el-select
          v-model="queryParams.deleted"
          placeholder="请选择是否删除"
          clearable
          style="width: 100%"
        >
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="用户状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择用户状态"
          clearable
          style="width: 100%"
        >
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
        >新增</el-button>
      </el-col>
      
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="用户唯一id" align="center" prop="uid" />
      <el-table-column label="用户名" align="center" prop="name" />
      <el-table-column label="昵称" align="center" prop="displayName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          {{ formatGender(scope.row.gender) }}
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" prop="portrait" width="80">
      <template slot-scope="scope">
          <img 
            v-if="scope.row.portrait" 
            :src="getImageUrl(scope.row.portrait)" 
            style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;"
            @error="handleImageError"
          />
          <el-avatar v-else :size="40" icon="el-icon-user-solid"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="手机" align="center" prop="mobile" />
      <!-- <el-table-column label="用户类型" align="center" prop="type" /> -->
      <el-table-column label="创建时间" align="center" prop="regTime" width="180">
      </el-table-column>
      <el-table-column label="最后在线时间" align="center" prop="lastTime" width="180">
      </el-table-column>
      <el-table-column label="用户状态" align="center" prop="userStatus">
        <template slot-scope="scope">
          <el-tag 
            :class="'status-' + scope.row.userStatus"
            :type="scope.row.userStatus == 1 ? 'warning' : (scope.row.userStatus == 2 ? 'danger' : '')">
            {{ scope.row.userStatusText || (scope.row.userStatus == 0 ? '正常' : (scope.row.userStatus == 1 ? '被禁言' : '被封禁')) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否在线" align="center" prop="online">
        <template slot-scope="scope">
          {{ scope.row.online == 0 ? '在线' : '离线' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
           size="mini" 
           type="text"
            icon="el-icon-edit" 
            @click="handleStatusUpdate(scope.row)"
            >修改状态</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
          >删除</el-button>
          
        </template>
         
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="displayName">
          <el-input v-model="form.displayName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select
            v-model="form.gender"
            placeholder="请选择性别"
            clearable
            style="width: 100%"
          >
            <el-option label="男" :value="1" />
            <el-option label="女" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="portrait">
          <el-upload
            class="avatar-uploader"
            :action="upload.url"
            :headers="upload.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
          >
            <img 
              v-if="form.portrait" 
              :src="getImageUrl(form.portrait)" 
              class="avatar" 
              @error="handleImageError"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div v-if="form.portrait" class="avatar-url-display">
            <el-button size="mini" type="text" @click="clearAvatar">清除头像</el-button>
          </div>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="扩展字段" prop="extra">
          <el-input v-model="form.extra" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
     <!-- 修改用户状态对话框 -->
    <el-dialog title="修改用户状态" :visible.sync="statusOpen" width="400px" append-to-body>
      <el-form ref="statusForm" :model="statusForm" label-width="80px">
        <el-form-item label="用户名称">
          <el-input v-model="statusForm.userName" :disabled="true" />
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-radio-group v-model="statusForm.status">
            <!-- <el-radio :label="0">正常</el-radio> -->
            <el-radio :label="1">禁言</el-radio>
            <el-radio :label="2">封禁</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStatusForm()">确 定</el-button>
        <el-button @click="cancelStatus">取 消</el-button>
      </div>
    </el-dialog>
  </div>

  
</template>

<script>
import { listUser, getUser,  addUser, updateUser, setUserStatus } from "@/api/zl/user"
import request from "@/utils/request"

export default {
  name: "User",
  data() {
    return {
      // 加载中
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 修改用户状态弹窗显示状态
      statusOpen: false,
      // Remove this duplicate upload data property
      // upload: {
      //   // 设置上传的请求头部
      //   headers: {},
      //   // 上传的地址
      //   url: process.env.VUE_APP_BASE_API + "/common/upload"
      // },
      statusForm:{
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uid: null,
        name: null,
        displayName: null,
        gender: null,
        portrait: null,
        mobile: null,
        email: null,
        address: null,
        company: null,
        social: null,
        passwdMd5: null,
        salt: null,
        extra: null,
        type: null,
        dt: null,
        createtime: null,
        regTime: null,
        online: null,
        lastTime: null,
        deleted: null,
        external: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        uid: [
          { required: true, message: "用户唯一id不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        dt: [
          { required: true, message: "注册/更新时间 时间戳不能为空", trigger: "blur" }
        ],
        createtime: [ 
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        userStatus: [
          { required: true, message: "用户状态不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList();
    // Remove this line since computed property handles headers automatically
    // this.upload.headers = { Authorization: "Bearer " + this.getToken() };
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = parseInt(response.total) || 0
        this.loading = false
      }).catch(error => {
        console.error('获取用户列表失败:', error)
        this.loading = false
        this.$modal.msgError('获取用户列表失败，请重试')
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        uid: null,
        name: null,
        displayName: null,
        gender: null,
        portrait: null,
        mobile: null,
        email: null,
        address: null,
        company: null,
        social: null,
        passwdMd5: null,
        salt: null,
        extra: null,
        type: null,
        dt: null,
        createtime: null,
        regTime: null,
        online: null,
        lastTime: null,
        deleted: null,
        external: null,
        status: 1,
        userStatus: 0
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加用户"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改"
      })
    },
/** 修改用户状态按钮操作 */
    handleStatusUpdate(row) {
      if (row && row.uid) {
        // 单个用户状态修改
        this.statusForm = {
          uid: row.uid,
          userName: row.name || row.displayName,
          status: row.userStatus || 0
        }
        this.statusOpen = true
      } else {
        this.$modal.msgError("请选择一个用户进行状态修改")
        return
      }
    },
    /** 提交状态修改 */
    submitStatusForm() {
      setUserStatus(this.statusForm.uid, this.statusForm.status).then(() => {
        this.$modal.msgSuccess("状态修改成功")
        this.statusOpen = false
        this.getList()
      }).catch(error => {
        console.error('修改用户状态失败:', error)
        this.$modal.msgError('修改用户状态失败，请重试')
      })
    },
    /** 取消状态修改 */
    cancelStatus() {
      this.statusOpen = false
      this.statusForm = {}
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(() => {
        // 改为调用更新接口进行逻辑删除
        const updateData = {
          id: ids,
          deleted: 1
        }
        return updateUser(updateData)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 用户状态修改 */
    handleStatusChange(row, newStatus) {
      const statusText = {
        0: '正常',
        1: '禁言',
        2: '封禁'
      }
      const text = statusText[newStatus]
      this.$modal.confirm('确认要将"' + row.name + '"用户设置为"' + text + '"状态吗？').then(() => {
        return setUserStatus(row.uid, parseInt(newStatus))
      }).then(() => {
        row.userStatus = parseInt(newStatus)
        this.$modal.msgSuccess("设置" + text + "成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 图片加载错误处理 */
    handleImageError(event) {
      // 图片加载失败时隐藏img标签
      event.target.style.display = 'none'
    },
    /** 获取图片完整URL */
    getImageUrl(url) {
      if (!url) return ''
      // 清理URL中的空格和反引号
      url = url.trim().replace(/`/g, '');

      // 如果是OSS的完整URL，通过后端下载接口访问
      if (url.startsWith('https://') && url.includes('aliyuncs.com')) {
        return process.env.VUE_APP_BASE_API + '/common/download?fileName=' + encodeURIComponent(url) + '&delete=false'
      }
      
      // 如果已经是完整的HTTP/HTTPS URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url
      }
      
      // 否则拼接BASE_API
      return process.env.VUE_APP_BASE_API + url
    },
    /** 头像上传成功处理 */
    handleAvatarSuccess(res, file) {
      console.log('上传响应:', res);
      
      if (res.code === 200) {
        // 后端返回的是完整的阿里云OSS URL，需要清理空格和反引号
        let avatarUrl =  res.url;
        let avatarUrlPath =  res.fileName;

        
        // 清理URL中的空格、反引号和双引号
        if (avatarUrl) {
          avatarUrl = avatarUrl.trim().replace(/[`"]/g, '');
        }
         if (avatarUrlPath) {
          avatarUrlPath = avatarUrlPath.trim().replace(/[`"]/g, '');
        }
        
        this.form.portrait = avatarUrl;
        this.form.portraitPath = avatarUrlPath;

        this.$message.success('头像上传成功');
        
        // 强制更新视图
        this.$nextTick(() => {
          this.$forceUpdate();
        });
      } else {
        this.$message.error(res.msg || '上传失败');
      }
    },
    /** 头像上传前的校验 */
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    /** 清除头像 */
    clearAvatar() {
        if (this.form.portraitPath) {
        console.log('当前头像URL:', this.form.portraitPath);
        // 调用后端删除文件接口
        this.deleteFile(this.form.portraitPath).then(() => {
          this.form.portrait = null
          this.$modal.msgSuccess("头像已清除")
        }).catch(() => {
          // 即使删除失败也清除表单字段
          this.form.portraitPath = null
          this.$modal.msgSuccess("头像已清除")
        });
      }
      
      // 清除表单中的头像字段
      this.form.portrait = '';
      
      // 强制更新视图
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },

    /** 获取token */
    getToken() {
      return this.$store.getters.token;
    },
    
    /** 删除文件 */
    deleteFile(fileName) {
      return request({
        url: '/common/delete',
        method: 'post',
        data: fileName,
        headers: {
          'Content-Type': 'text/plain'
        }
      })
    },
        /** 格式化性别显示 */
    formatGender(gender) {
      if (gender === 0 || gender === '0') {
        return '女';
      } else if (gender === 1 || gender === '1') {
        return '男';
      } else {
        return '未知';
      }
    }
  },
  computed: {
      // 文件上传配置
      upload() {
        return {
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + this.getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload"
        }
      }
    }
  }

</script>

<style scoped>
.status-0 {
  background-color: #409EFF !important;
  border-color: #409EFF !important;
  color: white !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  display: block;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.avatar-url-display {
  margin-top: 8px;
  text-align: center;
}
</style>




